package com.tcs.test.netty.client.channel;

import com.tcs.model.ipdata.IpDataBean;
import com.tcs.test.netty.client.NettyClient;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class TwoInChannel extends ChannelInboundHandlerAdapter {

    private final Logger logger = LoggerFactory.getLogger(TwoInChannel.class);

    private NettyClient nettyClient;

    public TwoInChannel() {
        nettyClient = new NettyClient();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("第2个channelHeader 接收到了: {} " , msg.toString());
        IpDataBean ipDataBean = (IpDataBean)msg;
        ipDataBean.setPort(3333);
        ctx.channel().writeAndFlush(ipDataBean).addListener(ChannelFutureListener.CLOSE);
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("第2个channelHeader 是否活动: {} ");
        ByteBuf byteBuf = Unpooled.copiedBuffer("客户端发送$".getBytes());
        ctx.channel().writeAndFlush(byteBuf);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info("第2个channelHeader 接受到: {} ");
        ctx.flush();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("第2个channelHeader 失去了链接 ");
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                nettyClient.go();
            }
        },1L, TimeUnit.SECONDS);
    }

}
